package com.app.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.app.model.Role;
import com.app.model.RoleMenu;

@Repository
public class RoleMenuDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	public void update(String[] checkedIds,String[] uncheckedIds,Long roleId) {
		String sql = "select * from auth_role_menu where menuId = ? and roleId = ?";
		for(String checked : checkedIds){
			Object args[] = {Long.parseLong(checked),roleId};
			RoleMenu rm = null;
			try{
				rm= jdbcTemplate.queryForObject(sql, args, new BeanPropertyRowMapper(RoleMenu.class));
			}catch (EmptyResultDataAccessException e) {
	            e.printStackTrace();
	        }		
			if(rm == null){
				String savesql = "insert into auth_role_menu(menuId,roleId) values(?,?)";   
		        jdbcTemplate.update(savesql, args);  
			}
		}
		for(String unchecked : uncheckedIds){
			Object args[] = {Long.parseLong(unchecked),roleId};
			RoleMenu rm = null;
			try{
				rm= jdbcTemplate.queryForObject(sql, args, new BeanPropertyRowMapper(RoleMenu.class));
			}catch (EmptyResultDataAccessException e) {
	            e.printStackTrace();
	        }	
			if(rm != null){
				String deletesql = "delete from auth_role_menu where menuId=? and roleId = ?";   
		        jdbcTemplate.update(deletesql, args);  
			}
		}
		
	}

	public List<Long> getMenuIdList(Long roleId) {
		String sql = "select menuId from auth_role_menu where roleId = ?";
		Object args[] = {roleId};
		return jdbcTemplate.queryForList(sql, args, Long.class);
		
	}
 
}
